package com.founder.gateway.system.util;

import com.founder.gateway.component.transport.netty.exception.NettyException;
import org.setu.framework.utils.DateTimeHelper;

import java.util.Date;

import static com.founder.gateway.system.consts.ApiSetuErrorCode.API_REQUEST_PARAM_VERIFY;

/**
 * 参数校验 EL表达式
 */
public class ParamsVerifyUtil {
    private static final String TIME_FORMAT_ERROR = "时间格式错误！";
    private static final String START_FORMAT_ERROR = "开始" + TIME_FORMAT_ERROR;
    private static final String END_FORMAT_ERROR = "结束" + TIME_FORMAT_ERROR;

    public static final ParamsVerifyUtil INSTANCE = new ParamsVerifyUtil();

    private ParamsVerifyUtil() {
    }

    /**
     * null 检查
     */
    public <T> T checkNull(T value, String hint) throws NettyException {
        if (value == null) {
            throw new NettyException(API_REQUEST_PARAM_VERIFY, hint);
        }
        return value;
    }

    /**
     * String 转 Date
     */
    public Date parseToDate(String text) throws NettyException {
        return parseToDate(text, TIME_FORMAT_ERROR);
    }

    /**
     * String 转 Date
     */
    public Date parseToDate(String text, String hint) throws NettyException {
        try {
            return checkNull(DateTimeHelper.parseToDate(text), hint);
        } catch (Exception e) {
            throw new NettyException(API_REQUEST_PARAM_VERIFY, hint);
        }
    }

    /**
     * 时间先后检查
     */
    public boolean start2end(String start, String end) throws NettyException {
        return start2end(start, end, START_FORMAT_ERROR, END_FORMAT_ERROR);
    }

    /**
     * 时间先后检查
     */
    public boolean start2end(String start, String end, String startHint, String endHint) throws NettyException {
        return parseToDate(start, startHint).before(parseToDate(end, endHint));
    }

    /**
     * 时间差转秒
     */
    public long range2second(String start, String end) throws NettyException {
        return range2second(start, end, START_FORMAT_ERROR, END_FORMAT_ERROR);
    }

    /**
     * 时间差转秒
     */
    public long range2second(String start, String end, String startHint, String endHint) throws NettyException {
        return (parseToDate(end, endHint).getTime() - parseToDate(start, startHint).getTime()) / 1000;
    }

    /**
     * 字符串格式化
     */
    public String format(String format, Object... args) {
        return String.format(format, args);
    }
}
